package fm.dongman.modellib.remote;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import fm.dongman.animefm.contractlib.contract.HomeContract;
import fm.dongman.animefm.contractlib.model.HomeDataModel;
import fm.dongman.modellib.RemoteHelper;
import fm.dongman.modellib.StaticArea.StaticUrl;

/**
 * 首页网络获取数据
 * Created by shize on 2017/10/10.
 */

public class HomeRemoteDataSource implements HomeContract.IHomeDataSource {
    private static HomeRemoteDataSource INSTANCE; // 持有实例

    //网络解析操作类
    private RemoteOperationHelper mRemoteOperationHelper;

    /**
     * @return 获取网络数据源实例
     */
    public static HomeRemoteDataSource getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new HomeRemoteDataSource();
        }
        return INSTANCE;
    }

    private HomeRemoteDataSource() {
        // 私有化对象
        mRemoteOperationHelper = RemoteOperationHelper.getOperationHelper();
    }

    @Override
    public void getData(@NotNull LoadSourceCallback<? super HomeDataModel> callback) {
        JSONObject jsonObject = RemoteHelper.Companion.getInstance().parseGetUrl(StaticUrl.HOME_REMOTE);
        if (jsonObject == null) {
            // 检测连接是否成功
            callback.onDataLoadFiled();
            return;
        }
        HomeDataModel homeDataModel = new HomeDataModel();
        homeDataModel.setBanners(mRemoteOperationHelper.downBanner(jsonObject));
        homeDataModel.setFMRecommends(mRemoteOperationHelper.downFMRecommends(jsonObject));
        homeDataModel.setNewArticles(mRemoteOperationHelper.downArticle(jsonObject));
        homeDataModel.setNewComments(mRemoteOperationHelper.downComment(jsonObject));
        homeDataModel.setSheets(mRemoteOperationHelper.downSheet(jsonObject));
        homeDataModel.setRankComic(mRemoteOperationHelper.downRankComic(jsonObject));

        callback.onDataLoaded(homeDataModel);
    }

    @Override
    public void saveData(HomeDataModel dataModel) {
        // 不需要做操作，因为保存数据操作是在 HomeRepository 里进行操作的
    }

    @Override
    public void refreshData() {
        // 不需要做操作，因为刷新数据操作是在 HomeRepository 里进行操作的
    }

    @Override
    public void offLine() {
        // 不需要做操作
    }
}
